package com.netintech.project.system.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

/**
 * WebSocket：每个连接各自的服务端对象 每连接一个对象，spring就自动新建一个WebSocketServer对象
 * webSocketSet：所有WebSocket对象集合
 * userId：每个WebSocket对象的id标识
 * 加入报警模块业务代码
 */
@Slf4j
@ServerEndpoint("/alarmWebsocket/{userId}")
@Component
public class AlarmWebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    // 因为spring容器默认是单例模式，每次产生新连接，生成新的WebSocketServer对象，前一个连接对象就被覆盖了，所以需要保存到这个集合中
    private static CopyOnWriteArraySet<AlarmWebSocketServer> webSocketSet = new CopyOnWriteArraySet<AlarmWebSocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //接收userId
    private String userId = "";

//    public static AlarmService alarmService;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private static final DateTimeFormatter FORMATTER2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


//    @Autowired
//    public void setUsersService(AlarmService alarmService) {
//        AlarmWebSocketServer.alarmService = alarmService;
//    }


    /**
     * 连接建立成功调用的方法
     * userId接收前端传过来的参数，
     *
     * @PathParam("userId") 注解获取 @ServerEndpoint("/websocket/{userId}")注解中的参数
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("alarmWebsocket有新窗口开始监听:" + userId + ",当前在线人数为" + getOnlineCount());
        this.userId = userId;
//        try {
////            连接ws成功后，发送表中当日所有的报警数据
//            Map<String, Object> map = new HashMap<>();
//            map.put("date", FORMATTER.format(LocalDate.now()));
//            map.put("descOrder", true);
//            List<AlarmHistory> alarmHistoryList = alarmService.queryAlarm(map);
//            alarmHistoryList = alarmHistoryList.stream().peek(
//                    a -> {
//                        a.setAlarmTimeStr(FORMATTER2.format(a.getAlarmTime()));
//                        if (Objects.equals("1", a.getLevel())) {
//                            a.setLevel("重点人员");
//                        }
//                    }
//            ).collect(Collectors.toList());
//            sendMessage(OBJECT_MAPPER.writeValueAsString(alarmHistoryList));
//            log.info("发送当日报警数据" + alarmHistoryList.size() + "条");
//        } catch (IOException e) {
//            e.printStackTrace();
//            log.error(e.getMessage());
//        }

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("alarmWebsocket有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("alarmWebsocket收到来自窗口" + userId + "的信息:" + message);
//        //收到消息后，群发该消息（全部群发）
//        for (AlarmWebSocketServer item : webSocketSet) {
//            try {
//                item.sendMessage("服务端接收到信息后群发："+message);
//            } catch (IOException e) {
//                e.printStackTrace();
//                log.error(e.getMessage());
//            }
//        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, String userId){
        log.info("推送消息到窗口" + userId + "，推送内容:" + message);
        log.info("sendInfo方法的webSocketSet大小为：" + webSocketSet.size());
        for (AlarmWebSocketServer item : webSocketSet) {
//            synchronized (item) {
            try {
                //这里可以设定只推送给这个userId的，为null则全部推送
                if (userId == null) {
//            	    防止给断开的连接，发数据，报错导致阻塞
                    if (item.session.isOpen()) {
                        item.sendMessage(message);
                    }
                } else if (item.userId.equals(userId)) {
                    if (item.session.isOpen()) {
                        item.sendMessage(message);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.error(e.getMessage());
            }
        }
    }

    /**
     * 给指定集合内的用户发送消息
     */
    public static void sendInfoByList(String message, List<String> userIds){
        log.info("推送消息到窗口" + userIds + "，推送内容:" + message);
        log.info("sendInfo方法的webSocketSet大小为：" + webSocketSet.size());
        if (CollectionUtils.isEmpty(userIds)) {
            return;
        }
        for (String userId : userIds) {
            for (AlarmWebSocketServer alarmWebSocketServer : webSocketSet) {
                if (alarmWebSocketServer.session.isOpen() && Objects.equals(userId, alarmWebSocketServer.userId)) {
                    try {
                        alarmWebSocketServer.sendMessage(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
//                    不能break，webSocketSet中可能有多个用户id相同的对象
                }
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        AlarmWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        AlarmWebSocketServer.onlineCount--;
    }
}